/**
 * @copyright 2016 Indie Semiconductor.
 *
 * This file is proprietary to Indie Semiconductor.
 * All rights reserved. Reproduction or distribution, in whole
 * or in part, is forbidden except by express written permission
 * of Indie Semiconductor.
 *
 * @file clock_device.c
 */

#include "clock_device.h"

#define SYSTEM_CLOCK_HIGH_FREQ  (16000000)
#define SYSTEM_CLOCK_LOW_FREQ   (10000)
uint32_t systemClock = SYSTEM_CLOCK_LOW_FREQ;

void Clock_SystemMainClockInit(ClockSource_t clock, ClockDivider_t divider)
{
    if (clock == CLOCK_RC_16MHz){
        CRGA_SFRS->SYSCLKCTRL.HFRCENA = 1;
        while(CRGA_SFRS->SYSCLKCTRL.HFRCSTS == 0);
        SYSCTRLA_SFRS->TRIMKEY = 0x1d155afe;
        SYSCTRLA_SFRS->TRIM_HF_RC = HWCFG_GetRCHFClockCalibValue();
        SYSCTRLA_SFRS->TRIMKEY = 0;
        systemClock = SYSTEM_CLOCK_HIGH_FREQ;
    }else{
        CRGA_SFRS->KILLLFRC = 0;
        SYSCTRLA_SFRS->TRIMKEY = 0x1d155afe;
        SYSCTRLA_SFRS->TRIM_LF_RC = HWCFG_GetRCLFClockCalibValue();
        SYSCTRLA_SFRS->TRIMKEY = 0;
        systemClock = SYSTEM_CLOCK_LOW_FREQ;
    }
    CRGA_SFRS->SYSCLKCTRL.SYSCLKSEL = clock;
    CRGA_SFRS->SYSCLKCTRL.DIVSYSCLK = divider;
//    SYSCTRLA_SFRS->TRIM_ACCESS_KEY.TRIM_LOCK = 1; //Lock Trim until reset
    systemClock = systemClock/(1 << clock);
  
    /* disable test mux */
    IOCTRLA_SFRS->ENA = 0x00;
    
}

uint32_t Clock_GetSystemClock(void)
{
    return systemClock;
}
